//添加上架商品
import React, { useState, useEffect } from 'react';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate, useLocation } from 'react-router-dom';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { Input, Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message, Collapse } from 'antd';
import { initAdd, findTwo, findGoodsByIdNotInVo,addToPro } from '../../../api/promotion';
import { values } from 'mobx';
interface DataType {
    id: number;//序号
    img: string;//图片
    name: string;//名称
    sernum: string;//货号
    rec: string;//分类
    sell: number;//销量

}
export default function AddCommodity() {
    const [data, setData] = useState<DataType[]>();//装表格内容
    const [allBrand, setAllBrand] = useState<any>()//装所有品牌
    const [allOne, setAllOne] = useState<any>()//装所有一级分类
    const [allTow, setAllTow] = useState<any>()//装所有一级分类
    const [page, setPage] = useState(1)//页码
    const [pageSize, setPagesize] = useState(5)//一页几条
    const [count, setCount] = useState<number>()
    const location = useLocation()
    const [id, setID] = useState<number>() //id
    const { Panel } = Collapse;
    const navigate = useNavigate()
    // 表格标题
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '商品图片',
            dataIndex: 'img',
            render: (_, record) => (
                <Image
                    width={50}
                    height={50}
                // src="https://img0.baidu.com/it/u=3007048469,3759326707&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677690000&t=6631b97b2d291cb6ca173fa887f1ea71"
                />
            ),
        },
        {
            title: '商品名称',
            dataIndex: 'name',
        },
        {
            title: '货号',
            dataIndex: 'sernum',
        },
        {
            title: '价格',
            dataIndex: 'price',
        },
        {
            title: '分类',
            dataIndex: 'rec',
        },
        {
            title: '品牌',
            dataIndex: 'rec',
        },
        {
            title: '销量',
            dataIndex: 'sell',
        },
        {
            title: '操作',
            dataIndex: 'adds',
            render: (_, record) => (
                <Space size="middle">
                    <Button id='del'
                    onClick={() => showModal(record)} 
                    >添加</Button>
                </Space >
            ),
        },
    ];

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };


    //重置
    const resetting = () => {
        message.success('重置成功！')
    }

    //返回上一页
    const goBackPage = () => {
        window.history.back()
    }
    //获取页码
    const Change = (page: number, pageSize: number) => {
        console.log(page, pageSize);
        setPage(page)
        setPagesize(pageSize)
    }

    useEffect(() => {
        console.log('id', location.state.id);
        InitAdd()
        FindGoodsByIdNotInVo()
    }, [page, pageSize])


    //获取表格内容
    const FindGoodsByIdNotInVo = () => {
        findGoodsByIdNotInVo({
            pro: location.state.id,
        }).then(res => {
            console.log('查询表格成功', res);
            if (res.code == '200') {
                setData(res.data.goods)
            }
        }).catch(err => {
            console.log('查询表格失败', err);
        })
    }

    //获取所有品牌
    const InitAdd = () => {
        initAdd(null).then(res => {
            // console.log('查询运动成功', res);
            const allOne = res.data.allOne.map((item: { name: any; id: any; }) => ({
                value: item.id,
                label: item.name
            }))
            setAllOne(allOne)
            const allBrand = res.data.allBrand.map((item: { name: any; id: any; }) => ({
                value: item.id,
                label: item.name
            }))
            setAllBrand(allBrand)
        }).catch(err => {
            console.log('查询运动失败', err);
        })
    }

    //查询
    const onFinish = (values: any) => {
        console.log('values', values);

    }

    //一级分类状态
    const handleChange = (value: any) => {
        console.log('one', value)
        findTwo({
            id: value,
        }).then(res => {
            console.log('查询二级分类成功', res);
            const allTow = res.data.map((item: { name: any; id: any; }) => ({
                value: item.id,
                label: item.name
            }))
            setAllTow(allTow)
        }).catch(err => {
            console.log('查询二级分类失败', err);
        })
    }

    //二级分类状态
    const dleChange = (value: any) => {
        console.log('tow', value)
    }

    //品牌状态
    const andleChange = (value: any) => {
        console.log('v', value)
    }

    //添加到促销里面
    const showModal = (record: any) => {
        console.log('OK', record);
        addToPro({
            pro:location.state.id,
            goods:record.id,
        }).then(res => {
            console.log('添加成功', res);
          }).catch(err => {
            console.log('添加失败', err);
          })
          message.success('添加成功！')
      };
    return (
        <div>
            <Space>
                <Button className='return' onClick={goBackPage}>返回</Button>
            </Space>
            {/* 标题 */}
            <p className="head">添加商品</p>
            {/* 操作 */}
            <Collapse className='collapse' defaultActiveKey={['1']}>
                <Panel header="筛选查询" key="1">
                    <div className='operate-wrap'>
                        <Form className='operate-left operate-left-item' onFinish={onFinish}>
                            <Form.Item label="关键词：" className='operate-left-item' name='keyword' initialValue=''>
                                <Input placeholder="商品名称/商品货号" className='search' />
                            </Form.Item>
                            <Form.Item label='分类：' className='operate-left-item' name='state'>
                                <Select
                                    placeholder="请选择一级分类"
                                    onChange={handleChange}
                                    style={{ width: 150 }}
                                    allowClear
                                    options={allOne}
                                    className='drop'
                                />
                            </Form.Item>
                            <Form.Item className='operate-left-item' name='towstate'>
                                <Select
                                    placeholder="请选择二级分类"
                                    onChange={dleChange}
                                    style={{ width: 150 }}
                                    allowClear
                                    options={allTow}
                                    className='drop'
                                />
                            </Form.Item>
                            <Form.Item label='品牌：' className='operate-left-item' name='allBrand'>
                                <Select
                                    placeholder="全部"
                                    onChange={andleChange}
                                    style={{ width: 150 }}
                                    allowClear
                                    options={allBrand}
                                    className='drop'
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
                                <Button className='reset operate-left-item' onClick={resetting} >重置</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </Panel>
            </Collapse>
            {/* 表格 */}
            <div className='table'>
                {/* 表格操作 */}
                <div className='operationTable'>
                    {/* 排序 */}
                    <Form>
                        <Form.Item label='排序：' className='operate-left-item' name='state'>
                            <Space wrap>
                                <Select
                                    // onChange={handleChange}
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '按时间倒序', label: '按时间倒序' }, { value: '按时间顺序', label: '按时间顺序' }]}
                                    className='drop'
                                />
                            </Space>
                        </Form.Item>
                    </Form>
                    <Button className='add'>批量添加</Button>
                </div>
                {/* 表格 */}
                <ConfigProvider locale={zh_CN}>
                    <Table rowSelection={rowSelection} columns={columns} rowKey={item => item.id} dataSource={data} pagination={{
                        position: ['bottomRight'],
                        pageSizeOptions: [3, 5, 10, 15],
                        showQuickJumper: true,
                        showSizeChanger: true,
                        onChange: Change,
                        pageSize: pageSize,
                        total: count,
                    }} />
                </ConfigProvider>
            </div>
        </div>
    )
}